package com.viboo.concern.controller;

import com.google.gson.Gson;
import com.viboo.concern.entity.ChatToken;
import com.viboo.concern.entity.User;
import com.viboo.concern.response.Result;
import com.viboo.concern.response.ResultEnum;
import com.viboo.concern.response.ResultUtil;
import com.viboo.concern.service.impl.UserServiceImpl;
import com.viboo.concern.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avanline
 * @descriotion
 * @date 2018-03-02 20:08
 */
@RestController
@RequestMapping("share")
@Slf4j
public class ShareController {

    @Autowired
    UserServiceImpl userService;

    @GetMapping("image")
    Result<?> getShareImage(String userId, String avatar, HttpServletRequest request, HttpServletResponse response){

        if (TextUtils.isEmpty(userId))
            return ResultUtil.error("用户ID为空");
        String access_token = null;
        try {
            access_token  = WeChatUtil.getToken();
        } catch (BaseException e) {
            e.printStackTrace();
            log.info("获取token失败:{},code:{}",e.msg,e.code);
        }
        Result<?> mQrCodeResult = getXcxQrCode(access_token, userId);
        if (mQrCodeResult.getCode() != ResultEnum.SUCCESS.getCode())
            return mQrCodeResult;
        BufferedImage mBufferedImage = (BufferedImage) mQrCodeResult.getData();
        if (mBufferedImage == null)
            return ResultUtil.error("获取小程序码错误");
        String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();//项目图片路径
        String projectUrl = path + ("/images/bg_qr_code.jpg");//背景图片
        BufferedImage shareImg = createImage(projectUrl, avatar, mBufferedImage);
        if (shareImg == null)
            return ResultUtil.error("绘制分享图片失败");
        String savePath = request.getSession().getServletContext().getRealPath("/");
        savePath = savePath + "/WEB-INF/classes/static/images";
        String fileName = System.currentTimeMillis() + ".jpg";

        try {
            saveQrCode(shareImg, new FileOutputStream(new File(savePath, fileName)), "jpg");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("保存分享图片失败");
        }
        path = "http://" + request.getServerName() + ":80"
                + request.getContextPath();//项目图片路径
        String sharePath = path + ("/images/") + fileName;

        updateShareTime(userId);//修改分享时间

        return ResultUtil.success(sharePath);
    }

    private void updateShareTime(String openId) {
        try {
            User mUser = userService.selectUser(openId);
            if (mUser.getShareTime() != 0)
                return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User();
        user.setOpenId(openId);
        try {
            userService.updateShareTime(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取小程序二维码
     *
     * @return
     */
    private Result<?> getXcxQrCode(String token, String userId) {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;

        Map<String, Object> map = new HashMap<>();
//        map.put("access_token", token);
        map.put("scene", userId);
        map.put("page", "pages/Anotherpage/Anotherpage");
        map.put("width", 320);
        map.put("auto_color", true);
//        Map<String, Object> line_color = new HashMap<>();
//        line_color.put("r", 10);
//        line_color.put("g", 20);
//        line_color.put("b", 30);
//        map.put("line_color", line_color);
        try {
            RestTemplate rest = new RestTemplate();
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(map, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);

            byte[] result = entity.getBody();
            log.info("返回数据长度:{}", result.length);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
            // 定义BufferedReader输入流来读取URL的响应
//            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
//            String line;
//            StringBuilder mStringBuilder = new StringBuilder();
//            while ((line = in.readLine()) != null) {
//                mStringBuilder.append(line);
//            }
//            log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + mStringBuilder.toString());
            BufferedImage mBufferedImage = ImageIO.read(inputStream);
            if (mBufferedImage == null) {
                return ResultUtil.error("获取小程序码错误");
            }
            return ResultUtil.success(mBufferedImage);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("获取小程序码错误");
        }
    }


    private BufferedImage createImage(String bgUrl, String avatar, BufferedImage qrImage) {
        int qrWidth = 160;
        int avatarWidth = 160;
        try {
            BufferedImage bgImage = ImageIO.read(new URL(bgUrl).openConnection().getInputStream());
            BufferedImage avatarImg = ImageIO.read(new URL(avatar).openConnection().getInputStream());
            // 以本地图片为模板
            Graphics2D g = bgImage.createGraphics();
            g.drawImage(qrImage, bgImage.getWidth() - qrWidth - 26, bgImage.getHeight() - qrWidth - 32, 160, 160, null);
            //处理图片将其压缩成正方形的小图
            //裁剪成圆形 （传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的）
            avatarImg = convertCircular(avatarImg);
            g.drawImage(avatarImg, 30, bgImage.getHeight() - qrWidth - 32, avatarWidth, avatarWidth, null);
            return bgImage;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 传入的图像必须是正方形的 才会 圆形  如果是长方形的比例则会变成椭圆的
     *
     * @return
     * @throws IOException
     */
    private BufferedImage convertCircular(BufferedImage bi1) throws IOException {
        //透明底的图片
        BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1, 0, 0, null);
        //设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }

    /**
     * 保存二维码图片
     *
     * @param image
     * @param outputStream
     * @param imageFormat
     * @throws IOException
     */
    private void saveQrCode(BufferedImage image, OutputStream outputStream, String imageFormat) throws IOException {
        ImageIO.write(image, imageFormat, outputStream);
    }

}
